package com.harmontronics.hanma.paas.paas.utils;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.google.common.collect.Lists;
import java.beans.FeatureDescriptor;
import java.beans.PropertyDescriptor;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;

public class MyBeanUtils {

    public static <T> T transform(Object src, Class<T> clazz) {
        if (src == null) {
            return null;
        } else {
            Object instance = null;
            try {
                instance = clazz.newInstance();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InstantiationException e) {
                e.printStackTrace();
            }
            org.springframework.beans.BeanUtils.copyProperties(src, instance, getNullPropertyName(src));
            return (T) instance;
        }
    }

    private static String[] getNullPropertyName(Object source) {
        BeanWrapper src = new BeanWrapperImpl(source);
        PropertyDescriptor[] pds = src.getPropertyDescriptors();
        List emptyNames = Arrays.stream(pds).filter(pd -> src.getPropertyValue(pd.getName()) == null)
                .map(FeatureDescriptor::getName).collect(Collectors.toList());
        String[] result = new String[emptyNames.size()];
        return (String[]) emptyNames.toArray(result);
    }

    public static <T> List<T> batchTransform(Class<T> clazz, List<? extends Object> srcList) {
        if (CollectionUtils.isEmpty(srcList)) {
            return Lists.newArrayList();
        } else {
            List<T> result = new ArrayList<>(srcList.size());
            Iterator var3 = srcList.iterator();
            while (var3.hasNext()) {
                Object srcObj = var3.next();
                result.add(transform(srcObj, clazz));
            }
            return result;
        }
    }

    /**
     * 复制非空属性的值
     * @param source
     * @param target
     */
    public static void copyNonNullProperties(Object source, Object target){
        org.springframework.beans.BeanUtils.copyProperties(source, target, getNullPropertyName(source));
    }

    public static void copyProperties(Object source, Object target,Class<?> editable){
        org.springframework.beans.BeanUtils.copyProperties(source, target, editable);
    }

    public static void copyProperties(Object source, Object target){
        org.springframework.beans.BeanUtils.copyProperties(source, target);
    }

}
